#!/bin/sh
# Generate rekeyvacuum.c from an SQLite3 amalgamation and write it to stdout.
# Usage: ./script/rekeyvacuum.sh sqlite3.c >rekeyvacuum.c

INPUT="$([ "$#" -eq "1" ] && echo "$1" || echo "sqlite3.c")"
if ! [ -f "$INPUT" ]; then
  echo "Usage: $0 <SQLITE3_AMALGAMATION>" >&2
  echo " e.g.: $0 sqlite3.c" >&2
  exit 1
fi

die() {
    echo "[-]" "$@" >&2
    exit 2
}

VERSION="$(sed -n 's/^#define SQLITE_VERSION[^"]*"\([0-9]\+\.[0-9]\+\.[0-9]\+\)"$/\1/p' "$INPUT")"
[ -z "$VERSION" ] && die "cannot find SQLite3 version (is '$INPUT' a valid amalgamation?)"

cat <<EOF
/*
** Adjusted version of sqlite3RunVacuum() to allow reducing reserved page space.
** For this purpose the number of reserved bytes per page is passed as an extra
** parameter to the adjusted function.
**
** Change 0: Rename function to sqlite3RekeyVacuum()
** Change 1: Add parameter 'int nRes'
** Change 2: Remove local variable 'int nRes'
** Change 3: Remove initialization 'nRes = sqlite3BtreeGetOptimalReserve(pMain)'
**
** Code generated by script/rekeyvacuum.sh from SQLite v$VERSION amalgamation.
*/
EOF
sed -n '/^SQLITE_PRIVATE .*int sqlite3RunVacuum([^;]*$/,/^}$/p' "$INPUT" \
    | sed 's/sqlite3RunVacuum/sqlite3RekeyVacuum/' \
    | sed 's/^\([^ )][^)]*\)\?){$/\1, int nRes){/' \
    | grep -v "int nRes;\|nRes = " \
    | grep "^" || die "Error generating rekeyvacuum.c"
